package service

import (
	"fmt"
	"software/core"
	"software/global"
	"software/models"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

// QueryAdminByUsername 根据用户名查询管理员
func QueryAdminByUsername(username string) (*models.Admin, error) {
	var admin models.Admin
	result := global.DB.Where("username = ?", username).First(&admin)
	if result.Error != nil {
		return nil, result.Error
	}
	return &admin, nil
}

// QueryUserById 根据ID查询用户
func QueryAdminById(id string) (interface{}, error) {
	var admin models.Admin
	result := global.DB.First(&admin, id)
	if result.Error != nil {
		return nil, result.Error
	}

	return admin, nil
}

// QueryAdminInfoById 根据ID查询管理员信息(不含密码)
func QueryAdminInfoById(id uint) (gin.H, error) {
	var admin models.Admin
	result := global.DB.First(&admin, id)
	if result.Error != nil {
		return nil, result.Error
	}

	// 返回不含密码的管理员信息
	adminInfo := gin.H{
		"id":         admin.ID,
		"username":   admin.Username,
		"avatar":     admin.Avatar,
		"created_at": admin.CreatedAt.Format("2006-01-02 15:04:05"),
		"gender":     admin.Gender,
		"phone":      admin.Phone,
		"email":      admin.Email,
		"profile":    admin.Profile,
	}

	return adminInfo, nil
}

// QueryAllUsers 查询所有用户
func QueryAllAdmins() ([]models.Admin, error) {
	var admins []models.Admin
	result := global.DB.Find(&admins)
	if result.Error != nil {
		return nil, result.Error
	}
	return admins, nil
}

// CreateUser 创建用户
func CreateAdmin(m *models.Admin) error {
	// 调用 HashPassword 加密密码
	hashedPassword, err := core.HashPassword(m.Password)
	if err != nil {
		return err
	}
	m.Password = hashedPassword

	// 插入数据库
	result := global.DB.Create(m)
	return result.Error
}

// UpdateUserById 根据ID更新用户信息
func UpdateAdminById(u uint, data map[string]interface{}) error {
	// 如果更新包含密码，调用 HashPassword 加密
	if newPassword, ok := data["password"].(string); ok {
		hashedPassword, err := core.HashPassword(newPassword)
		if err != nil {
			return err
		}
		data["password"] = hashedPassword
	}

	// 更新用户信息
	result := global.DB.Model(&models.Admin{}).Where("id = ?", u).Updates(data)
	return result.Error
}

// DeleteUser 根据ID删除用户
func DeleteAdmin(id string) error {
	result := global.DB.Delete(&models.Admin{}, id)
	return result.Error
}

/**
修改密码
*/

// ChangeAdminPassword 修改管理员密码
func ChangeAdminPassword(adminID uint, oldPassword, newPassword string) error {
	var admin models.Admin
	result := global.DB.Where("id = ?", adminID).First(&admin)
	if result.Error != nil {
		return fmt.Errorf("未找到该管理员")
	}

	// 验证旧密码是否正确
	err := bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(oldPassword))
	if err != nil {
		return fmt.Errorf("旧密码不正确")
	}

	// 加密新密码
	hashedPassword, err := core.HashPassword(newPassword)
	if err != nil {
		return err
	}

	// 更新密码
	result = global.DB.Model(&admin).Update("password", hashedPassword)
	return result.Error
}
